package com.laxcen.basiclib.core.task.core.thread;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.Set;

/**
 * 线程池配置类
 */
public class ThreadPoolConfig {

    // groupName为key
    private static final HashMap<String, IExecutorService> CACHE = new HashMap<>();

    private static final ThreadPoolConfig THREAD_POOL_CONFIG = new ThreadPoolConfig();

    private static final String DEFAULT_TAG = "ThreadPool";

    private ThreadPoolConfig() {
        newBuilder(DEFAULT_TAG).coreSize(1).priority(Thread.NORM_PRIORITY).asThreadPool();
    }

    IExecutorService getDefaultService() {
        return CACHE.get(DEFAULT_TAG);
    }

    IExecutorService getService(String groupName) {
        IExecutorService service = CACHE.get(groupName);
        return service == null ? getDefaultService() : service;
    }

    /**
     * 获取线程池组列表
     * @return
     */
    Set<String> getGroupNames() {
        return CACHE.keySet();
    }

    /**
     *
     * @param groupName 线程池组名称
     * @return
     */
    public static final Builder newBuilder(String groupName) {
        return new Builder(groupName);
    }

    public static final class Builder {
        private int coreSize;
        private String groupName;
        private int priority;

        private Builder(String groupName) {
            if (TextUtils.isEmpty(groupName)) {
                throw new IllegalArgumentException("groupName 不能为空");
            }
            this.groupName = groupName;
        }

        /**
         * @param priority 线程池的优先级
         * @see {@link Thread#MAX_PRIORITY } {@link Thread#MIN_PRIORITY} {@link Thread#NORM_PRIORITY}
         * @return
         */
        public Builder priority(int priority) {
            this.priority = priority;
            return this;
        }

        /**
         * 线程池中核心数
         * @param coreSize
         * @return
         */
        public Builder coreSize(int coreSize) {
            this.coreSize = coreSize;
            return this;
        }

        /**
         * 生成一个线程池
         * @return
         */
        public ThreadPoolConfig asThreadPool() {
            if (!CACHE.containsKey(groupName)) {
                IExecutorService executorService = ThreadPoolHandler.newBuilder(coreSize).groupName(groupName).priority(priority).builder()
                        .getExecutorService();
                CACHE.put(groupName, executorService);
            }
            return THREAD_POOL_CONFIG;
        }
    }
}
